package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.TreeProblem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 层次遍历
 * https://leetcode.com/problems/binary-tree-level-order-traversal/
 *
 * @author tzp
 * @since 2020/10/13
 */
public class LC102 implements TreeProblem {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return Collections.emptyList();
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> curLevel = new ArrayList<>();
        result.add(curLevel);

        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode seperator = root;//分层用
        while (queue.size() != 0) {
            TreeNode node = queue.poll();
            curLevel.add(node.val);
            if (node.left != null) queue.add(node.left);
            if (node.right != null) queue.add(node.right);

            if (node == seperator && queue.size() != 0) {
                seperator = queue.getLast();
                curLevel = new ArrayList<>();
                result.add(curLevel);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC102().levelOrder(treeNode));
    }
}
